//
//  XDQuickLookViewController.m
//  Pods-XDQuickLook_Example
//
//  Created by XiaoDev on 2018/11/30.
//

#import "XDQuickLookViewController.h"
@interface XDQuickLookViewController ()<QLPreviewControllerDataSource,QLPreviewControllerDelegate>

@end

@implementation XDQuickLookViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
    self.dataSource = self;
    self.currentPreviewItemIndex = self.currentIndex;
}
#pragma mark -- datasource协议方法
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
    if (self.xDelegate && [self.xDelegate respondsToSelector:@selector(xdnumberOfItemsInQuickLookController:)]) {
        return [self.xDelegate xdnumberOfItemsInQuickLookController:self];
    }
    return 0;
}

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
    if (self.xDelegate && [self.xDelegate respondsToSelector:@selector(xdQuickLookController:ItemAtIndex:)]) {
        NSString *path = [self.xDelegate xdQuickLookController:self ItemAtIndex:index];
//        if (![path hasPrefix:KDocumentP]) {
//            path = [KDocumentP stringByAppendingPathComponent:self.itemArray[index]];
//        }
        if ([path hasSuffix:@"txt"] || [path hasSuffix:@"TXT"]) {
            // 处理txt格式内容显示有乱码的情况
            NSData *fileData = [NSData dataWithContentsOfFile:path];
            // 判断是UNICODE编码
            NSString *isUNICODE = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
            // 还是ANSI编码（-2147483623，-2147482591，-2147482062，-2147481296）encoding 任选一个就可以了
            NSString *isANSI = [[NSString alloc] initWithData:fileData encoding:-2147483623];
            if (isUNICODE) {
            } else {
                NSData *data = [isANSI dataUsingEncoding:NSUTF8StringEncoding];
                [data writeToFile:path atomically:YES];
            }
            return [NSURL fileURLWithPath:path];
        } else {
            
            return [NSURL fileURLWithPath:path];
        }
    }
    return nil;
}
- (void)backButtonAction:(UIButton *)button {
    if (self.xDelegate && [self.xDelegate respondsToSelector:@selector(xdQuickLookVCWillDismiss:currentIndex:)]) {
        [self.xDelegate xdQuickLookVCWillDismiss:self currentIndex:self.currentPreviewItemIndex];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

@end
